package com.booking.springrestful.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;

import com.booking.springrestful.config.ConstantPropertiesUtils;
import com.booking.springrestful.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class OssServiceImpl implements OssService {
 
    @Override
    public String uploadFileAvatar(MultipartFile file){
 
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        String fileurl = null;
 
        //创建OSSClient实例。
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
 
        //获取上传文件输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //获取文件名称
        String fileName = file.getOriginalFilename();
 
        //保证文件名唯一，去掉uuid中的'-'
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        fileName = uuid +"/"+ fileName;
 
        //把文件按日期分类，构建日期路径：avatar/2019/02/26/文件名
        //String datePath = new Date().toString("yyyy/MM/dd");
        String datePath = String.valueOf(new Date().getTime());
        //拼接
        fileName = datePath + "/" + fileName;
 
        //调用oss方法上传到阿里云
        //第一个参数：Bucket名称
        //第二个参数：上传到oss文件路径和文件名称
        //第三个参数：上传文件输入流
        ossClient.putObject(bucketName, fileName, inputStream);

        // 设置有效期（100年后）
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 100);
        Date expiration = calendar.getTime();
        // 生成下载链接。
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);

        //关闭OSSClient
        ossClient.shutdown();
 
        return url.toString();
    }
}